<?php
/**
 * Created by PhpStorm.
 * User: wangan
 * Date: 2016/12/7
 * Time: 9:39
 */

namespace App\Http\Service;


use App\Models\Role;
use Illuminate\Support\Facades\DB;

class RoleService
{
    public static function getRoleListPageInit($pageSize=20,$searchVal=null){

        if(!empty($searchVal)){
            return Role::where('label','like','%'.$searchVal.'%')
                ->paginate($pageSize);
        }
        return Role::paginate($pageSize);
    }

    public static function createOneRole($roleData,$permissionsId=[]){
        DB::beginTransaction();
        try{
            $role = Role::create($roleData);
            unset($role->perms);
            if(!empty($permissionsId)){
                $role->givePermissions($permissionsId);
            }
        }
        catch(\Exception $e){
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }

    public static function getAllRoles(){
        return Role::all();
    }
    public static function getOneRoles($roleId){
        return Role::find($roleId);
    }

    public static function updateOneRole($roleData,$permissionsId=[]){
        DB::beginTransaction();
        try{
            $role = Role::find($roleData['id']);
            $role->detachPermissions($role->perms);
            $role->update($roleData);
            if(!empty($permissionsId)){
                $role->givePermissions($permissionsId);
            }
        }
        catch(\Exception $e){
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }

    public static function deleteOneRole($roleId){
        DB::beginTransaction();
        try{
            $role = Role::find($roleId);
            $role->detachPermissions($role->perms);
            $role->delete();
        }catch (\Exception $e){
            DB::rollBack();
            return false;
        }
        DB::commit();
        return true;
    }

    public static function getPermissionsByRoles($roleIds = []){
        return Role::select(['permissions.*'])
            ->leftJoin('permission_role','roles.id','=','permission_role.role_id')
            ->leftJoin('permissions', 'permissions.id','=','permission_role.permission_id')
            ->whereIn('roles.id',$roleIds)
            ->groupBy('permissions.id')
            ->orderBy('permissions.id','desc')
            ->get();

    }


}